<!-- 文化分类管理页面 -->
<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryPage, getCategoryForm, addCategory, updateCategory, deleteCategory } from '@/api/culture/category'

// 搜索参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 表格列配置
const columns = [
  { prop: 'id', label: 'ID', width: '80' },
  { prop: 'name', label: '分类名称', minWidth: '180' },
  { prop: 'code', label: '分类编码', width: '150' },
  { prop: 'sort', label: '排序', width: '100' },
  { prop: 'createTime', label: '创建时间', width: '180' },
  { prop: 'status', label: '状态', width: '100' }
]

// 状态选项
const statusOptions = ref([
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
])

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增分类')

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  code: '',
  sort: 0,
  description: '',
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '排序号必须为数字值', trigger: 'blur' }
  ]
}

const formRef = ref(null)

// 获取分类列表
const getCategoryList = () => {
  loading.value = true
  getCategoryPage(queryParams).then(res => {
    tableData.value = res.list || []
    total.value = res.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 处理分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page
  getCategoryList()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  getCategoryList()
}

// 打开新增对话框
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增分类'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  resetForm()
  
  // 获取详细表单数据
  loading.value = true
  getCategoryForm(row.id).then(res => {
    Object.assign(formData, res)
    loading.value = false
    dialogVisible.value = true
  }).catch(() => {
    loading.value = false
  })
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该分类吗？删除后相关文章将无法显示', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCategory(row.id).then(() => {
      ElMessage.success('删除成功')
      getCategoryList()
    }).catch(error => {
      ElMessage.error(error.message || '删除失败')
    })
  }).catch(() => {})
}

// 修改状态
const handleStatusChange = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}该分类吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 更新状态
    updateCategory(row.id, {
      ...row,
      status: newStatus
    }).then(() => {
      ElMessage.success(`${statusText}成功`)
      getCategoryList()
    }).catch(() => {
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(`${statusText}失败`)
    })
  }).catch(() => {
    // 取消操作，恢复原状态
    row.status = row.status === 1 ? 0 : 1
  })
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return
  
  formRef.value.validate((valid) => {
    if (valid) {
      const isUpdate = formData.id !== ''
      const apiMethod = isUpdate ? updateCategory(formData.id, formData) : addCategory(formData)
      
      apiMethod.then(() => {
        ElMessage.success(isUpdate ? '更新成功' : '添加成功')
        dialogVisible.value = false
        getCategoryList()
      }).catch(error => {
        ElMessage.error(error.message || (isUpdate ? '更新失败' : '添加失败'))
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.name = ''
  formData.code = ''
  formData.sort = 0
  formData.description = ''
  formData.status = 1
  
  // 延迟重置校验结果
  if (formRef.value) {
    nextTick(() => {
      formRef.value.resetFields()
    })
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getCategoryList()
}

// 重置搜索
const resetSearch = () => {
  queryParams.name = ''
  handleSearch()
}

// 页面加载时获取数据
onMounted(() => {
  getCategoryList()
})
</script>

<template>
  <div class="app-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
      <el-input
        v-model="queryParams.name"
        placeholder="搜索分类名称"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      />
      <el-button type="success" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 分类列表 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :min-width="column.minWidth"
      >
        <template #default="{ row }" v-if="column.prop === 'status'">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="() => handleStatusChange(row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 分类编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form :model="formData" :rules="rules" label-width="100px" ref="formRef">
        <el-form-item label="分类名称" prop="name" required>
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        
        <el-form-item label="分类编码" prop="code" required>
          <el-input v-model="formData.code" placeholder="请输入分类编码" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入分类描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 240px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
